<template>
  <div>
    <!-- 选择商品类型 -->
    <a-modal v-model:visible="selectGoodsType" width="550" :closable="false">
      <div v-if="!showGoodsTemplates" class="goods-type-list">
        <div
          v-for="(item, index) in goodsTypeWay"
          :key="index"
          class="goods-type-item"
          :class="{ 'active-goods-type': item.check }"
          @click="handleClickGoodsType(item)"
        >
          <img :src="item.img" alt="" />
          <div>
            <h2>{{ item.title }}</h2>
            <p>{{ item.desc }}</p>
          </div>
        </div>
      </div>
      <div v-else class="goods-type-list">
        <h4 @click="showGoodsTemplates = !showGoodsTemplates">返回</h4>
        <div class="goods-list-box">
          <a-scrollbar style="height: 400px; overflow: auto">
            <div
              v-for="(item, tempIndex) in goodsTemplates"
              :key="tempIndex"
              class="goods-type-item template-item"
              @click="handleClickGoodsTemplate(item)"
            >
              <img :src="item.thumbnail" />
              <div>
                <h2>{{ item.goodsName }}</h2>
                <p>{{ item.sellingPoint || '' }}</p>
              </div>
            </div>
          </a-scrollbar>
        </div>
      </div>
    </a-modal>
    <!-- 商品分类 -->
    <div class="content-goods-publish">
      <div class="goods-category">
        <ul v-if="categoryListLevel1.length > 0">
          <li
            v-for="(item, index) in categoryListLevel1"
            :key="index"
            :class="{ activeClass: category[0].id === item.id }"
            @click="handleSelectCategory(item, index, 1)"
          >
            <span>{{ item.name }}</span>
            <span>&gt;</span>
          </li>
        </ul>
        <ul v-if="categoryListLevel2.length > 0">
          <li
            v-for="(item, index) in categoryListLevel2"
            :key="index"
            :class="{ activeClass: category[1].id === item.id }"
            @click="handleSelectCategory(item, index, 2)"
          >
            <span>{{ item.name }}</span>
            <span>&gt;</span>
          </li>
        </ul>
        <ul v-if="categoryListLevel3.length > 0">
          <li
            v-for="(item, index) in categoryListLevel3"
            :key="index"
            :class="{ activeClass: category[2].id === item.id }"
            @click="handleSelectCategory(item, index, 3)"
          >
            <span>{{ item.name }}</span>
          </li>
        </ul>
      </div>
      <p class="current-goods-category">
        您当前选择的商品类别是：
        <span>{{ category[0].name }}</span>
        <span v-show="category[1].name">> {{ category[1].name }}</span>
        <span v-show="category[2].name">> {{ category[2].name }}</span>
      </p>
      <template v-if="selectedTemplate.goodsName">
        <Divider>已选商品模版:{{ selectedTemplate.goodsName }}</Divider>
      </template>
    </div>
    <!-- 底部按钮 -->
    <div class="footer">
      <div>
        <a-button type="primary" @click="selectGoodsType = true"
          >商品类型</a-button
        >
        <a-button type="primary" style="margin-left: 5px" @click="next"
          >下一步</a-button
        >
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, ref, watch } from 'vue';
  import { getDraftGoodsListData, getGoodsCategoryAll } from '@/api/goods';
  import { Message } from '@arco-design/web-vue';
  import getAssetsImages from '@/utils/assetsImages';

  const emit = defineEmits<{
    (e: 'change', val: any): void;
  }>();
  const props = defineProps({
    categoryData: {
      type: Array,
      default: () => {
        return [];
      },
    },
  });
  const selectGoodsType = ref(false);
  const showGoodsTemplates = ref(false);
  const goodsTemplates = ref<Array<any>>([]);
  const selectedTemplate = ref<any>({});
  const goodsType = ref('');
  const categoryListLevel1 = ref<Array<any>>([]); // 1级分类列表
  const categoryListLevel2 = ref<Array<any>>([]); // 2级分类列表
  const categoryListLevel3 = ref<Array<any>>([]); // 3级分类列表
  const category = ref([
    { name: '', id: '' },
    { name: '', id: '' },
    { name: '', id: '' },
  ]); // 商品分类选择数组
  const goodsTypeWay = ref([
    {
      title: '实物商品',
      img: getAssetsImages('goodsType1.png'),
      desc: '零售批发，物流配送',
      type: 'PHYSICAL_GOODS',
      check: false,
    },
    {
      title: '虚拟商品',
      img: getAssetsImages('goodsType2.png'),
      desc: '虚拟核验，无需物流',
      type: 'VIRTUAL_GOODS',
      check: false,
    },
    // {
    //     title: "商品模板导入",
    //     img: getAssetsImages("goodsTypeTpl.png"),
    //     desc: "商品模板，一键导入",
    //     check: false,
    // }
  ]);
  const getGoodsTemplate = () => {
    const params = {
      saveType: 'TEMPLATE',
      sort: 'create_time',
      order: 'desc',
      pageSize: 10,
      pageNumber: 1,
    };
    getDraftGoodsListData(params).then((res) => {
      if (res.data.success) {
        goodsTemplates.value.push(...res.data.result.records);
      }
    });
  };
  const handleClickGoodsTemplate = (val: any) => {
    selectedTemplate.value = val;
    selectGoodsType.value = false;
    emit('change', { tempId: val.id });
  };
  const handleClickGoodsType = (val: any) => {
    goodsTypeWay.value.forEach((item) => {
      item.check = false;
    });
    val.check = !val.check;
    if (!val.type) {
      getGoodsTemplate();
      showGoodsTemplates.value = true;
    } else {
      goodsType.value = val.type;
      selectedTemplate.value = {};
    }
  };
  // 查询下一级，商城商品分类
  const getNextLevelCategory = () => {
    getGoodsCategoryAll().then((res) => {
      if (res.data.success && res.data.result) {
        categoryListLevel1.value = res.data.result;
      }
    });
  };
  // 选择商城商品分类
  const handleSelectCategory = (row: any, index: number, level: number) => {
    if (level === 1) {
      category.value.forEach((cate) => {
        cate.name = '';
        cate.id = '';
      });
      category.value[0].name = row.name;
      category.value[0].id = row.id;
      categoryListLevel2.value = categoryListLevel1.value[index].children;
      categoryListLevel3.value = [];
    } else if (level === 2) {
      category.value[1].name = row.name;
      category.value[1].id = row.id;
      category.value[2].name = '';
      category.value[2].id = '';
      categoryListLevel3.value = categoryListLevel2.value[index].children;
    } else {
      category.value[2].name = row.name;
      category.value[2].id = row.id;
    }
  };
  // 下一步
  const next = () => {
    if (goodsType.value && selectedTemplate.value.goodsName) {
      Message.error('请选择商品类型');
    }
    if (!category.value[0].name) {
      Message.error('请选择商品分类');
    } else if (!category.value[2].name) {
      Message.error('必须选择到三级分类');
    } else if (category.value[2].name) {
      const params = {
        category: category.value,
        goodsType: goodsType.value,
      } as any;
      if (selectedTemplate.value.id) {
        params.tempId = selectedTemplate.value.id;
        emit('change', params);
      } else {
        emit('change', params);
      }
    }
  };
  onMounted(() => {
    getNextLevelCategory();
  });
  defineExpose({
    selectGoodsType,
  });
  // 修改商品分类，商品分类回显
  watch(() => props.categoryData, (val: any) => {
    if (val && val.length) {
      category.value = JSON.parse(JSON.stringify(val));
      categoryListLevel1.value.filter(item => {
        if (item.id === val[0].id) {
          if (val.length >= 2) {
            item.children.filter((item2: any) => {
              if (item2.id === val[1].id) {
                categoryListLevel2.value = item.children;
                if (val.length >= 3) {
                  item2.children.filter((item3: any) => {
                    if (item3.id === val[2].id) {
                      categoryListLevel3.value = item2.children;
                    }
                  });
                }
              }
            });
          }
          return item;
        }
      });
    }
  }, { deep: true, immediate: true });
</script>

<style lang="less" scoped>
  @import './addGoods.less';
</style>
